#-*- coding:utf-8 -*-

import httplib
import urllib

class SendMessage():
    #服务地址
    host = "yunpian.com"
    #端口号
    port = 80
    #版本号
    version = "v1"
    #查账户信息的URI
    user_get_uri = "/" + version + "/user/get.json"
    #通用短信接口的URI
    sms_send_uri = "/" + version + "/sms/send.json"
    #模板短信接口的URI
    sms_tpl_send_uri = "/" + version + "/sms/tpl_send.json"
    def __init__(self, mobile, text, apikey='c3a4c21891247389b76fdee88d5334a3', tpl_id=1, tpl_value='#code#=1234&#company#=安择网'):
        self.mobile = mobile
        self.text = text
        self.apikey = apikey
        self.tpl_id = tpl_id
        self.tpl_value = tpl_value

    def get_user_info(self):
        """
        取账户信息
        """
        conn = httplib.HTTPConnection(self.host, port=self.port)
        conn.request('GET', self.user_get_uri + "?apikey=" + self.apikey)
        response = conn.getresponse()
        response_str = response.read()
        conn.close()
        return response_str

    def send_sms(self):
        """
        通用接口发短信
        """
        params = urllib.urlencode({'apikey': self.apikey, 'text': self.text, 'mobile':self.mobile})
        headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
        conn = httplib.HTTPConnection(self.host, port=self.port, timeout=30)
        conn.request("POST", self.sms_send_uri, params, headers)
        response = conn.getresponse()
        response_str = response.read()
        conn.close()
        return response_str

    def tpl_send_sms(self):
        """
        模板接口发短信
        """
        params = urllib.urlencode({'apikey': self.apikey, 'tpl_id':self.tpl_id, 'tpl_value': self.tpl_value, 'mobile':self.mobile})
        headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
        conn = httplib.HTTPConnection(self.host, port=self.port, timeout=30)
        conn.request("POST", self.sms_tpl_send_uri, params, headers)
        response = conn.getresponse()
        response_str = response.read()
        conn.close()
        return response_str
"""
#coding='utf-8'
import SendMessage

if __name__=='__main__':
	apikey='c3a4c21891247389b76fdee88d5334a3'
	text='【安择网】您的验证码是1234'
	mobile='13524065877'
	sms = SendMessage.SendMessage(mobile, text)
	print sms.get_user_info()
	print sms.send_sms()
"""